package com.wocai.jrt.orgadmin.project.action;

import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;

import javax.inject.Inject;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.wocai.jrt.orgadmin.project.model.ProjectAttachment;
import com.wocai.jrt.orgadmin.project.model.ProjectGrade;
import com.wocai.jrt.orgadmin.project.model.ProjectWithBLOBs;
import com.wocai.jrt.orgadmin.project.service.spi.ProjectAttachmentService;
import com.wocai.jrt.orgadmin.project.service.spi.ProjectGradeService;
import com.wocai.jrt.orgadmin.project.service.spi.ProjectService;
import com.wocai.jrt.orgadmin.utils.MyFileUtils;
import com.wocai.jrt.orgadmin.utils.UserUtils;
import com.vteba.utils.id.ObjectId;
import com.vteba.web.action.GenericAction;
import com.vteba.web.action.JsonBean;

/**
 * 项目附件控制器
 * @author zhangyz
 * @date 2016-3-17 17:23:18
 */
@Controller
@RequestMapping("/projectAttachment")
public class ProjectAttachmentAction extends GenericAction<ProjectAttachment> {
	private static final Logger LOGGER = LoggerFactory.getLogger(ProjectAttachmentAction.class);
	private static final Pattern FILE = Pattern.compile("^(.*)+.(doc|pdf|txt|docx|xlsx|xls)$");
	
	@Inject
	private ProjectAttachmentService projectAttachmentServiceImpl;
	@Inject
	private ProjectService projectServiceImpl;
	@Inject
	private ProjectGradeService projectGradeServiceImpl;
	
	/***
	 * 上传尽调、评级文件 用@RequestParam注解来指定表单上的file为MultipartFile
	 * @param file
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/uploadRelatedFile")
	public JsonBean uploadRelatedFile(@RequestParam("relatedFile") MultipartFile file,String projectId,String type,String grade) {
		getHttpServletResponse().setHeader("X-Frame-Options", "SAMEORIGIN");
		return publicUplaodFile(file,projectId,type,grade);
	}
	
	/***
	 * 上传合同文件 用@RequestParam注解来指定表单上的file为MultipartFile
	 * @param file
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/uploadContractFile")
	public JsonBean uploadContractFile(@RequestParam("contractFile") MultipartFile file,String projectId,String type,String grade) {
		getHttpServletResponse().setHeader("X-Frame-Options", "SAMEORIGIN");
		return publicUplaodFile(file,projectId,type,grade);
	}
	
	
	/**
	 * 上传附件公共方法
	 * @return JsonBean
	 */
	public JsonBean publicUplaodFile(MultipartFile file,String projectId,String type,String grade){
		JsonBean jsonBean = new JsonBean();
		try {
			if (StringUtils.isBlank(projectId)) {
				LOGGER.info("projectId is not allowed null");
				jsonBean.setCode(0);
				jsonBean.setMessage("项目id不能为空！");
				getHttpServletResponse().setHeader("X-Frame-Options", "SAMEORIGIN");
				return jsonBean;
			}
			String fileName = file.getOriginalFilename();
			if (!FILE.matcher(fileName).matches()) {
				LOGGER.info("request file type not mach the required");
				jsonBean.setCode(0);
				jsonBean.setMessage("不能上传非法格式文件！");
				getHttpServletResponse().setHeader("X-Frame-Options", "SAMEORIGIN");
				return jsonBean;
			}

			ProjectAttachment paParam = new ProjectAttachment();
			paParam.setProjectId(projectId);
			paParam.setContractName(fileName);
			paParam.setType(Integer.valueOf(type));
			List<ProjectAttachment> result = projectAttachmentServiceImpl.pagedList(paParam);
			if (null != result && result.size() > 0) {
				LOGGER.info("request file have existed");
				jsonBean.setCode(0);
				jsonBean.setMessage("不能重复上传相同文件！");
				getHttpServletResponse().setHeader("X-Frame-Options", "SAMEORIGIN");
				return jsonBean;
			}

			// 发起请求的参数
			LOGGER.info("request file upload, filename=[{}]", fileName);

			// 上传文件
			String filePath = MyFileUtils.uploadFile(file, MyFileUtils.FILE_TYPE);
			LOGGER.info("upload file success, filePath=[{}]", filePath);
			//更新项目评级
			String gradeId = null;
			ProjectAttachment projectAttachment = new ProjectAttachment();
			if("4".equals(type)){
				gradeId = updateProjectGrade(projectId,grade);
			}
			projectAttachment.setGradeId(gradeId);
			projectAttachment.setId(ObjectId.get().toString());
			projectAttachment.setProjectId(projectId);
			projectAttachment.setUrl(filePath);
			projectAttachment.setEmployeeId(UserUtils.getUserId());

			projectAttachment.setContractName(fileName);
			projectAttachment.setFileType("." + fileName.split("\\.")[1]);
			projectAttachment.setType(Integer.valueOf(type));
			String orgId = projectServiceImpl.get(projectId).getOrgId();
			projectAttachment.setOrgId(orgId);
			projectAttachment.setCreateTime(new Date());
			projectAttachmentServiceImpl.save(projectAttachment);
			
			jsonBean.setCode(1);
			jsonBean.setMessage(SUCCESS);

			getHttpServletResponse().setHeader("X-Frame-Options", "SAMEORIGIN");
		} catch (Exception e) {
			LOGGER.error("upload file error, error=[{}]", e.getMessage());
			jsonBean.setCode(0);
			jsonBean.setMessage("上传失败！");
			getHttpServletResponse().setHeader("X-Frame-Options", "SAMEORIGIN");
		}
		return jsonBean;
	}
	/**
	 * 更新项目评级
	 * @param projectId
	 * @return
	 */
	 private String updateProjectGrade(String projectId,String grade) {
		 String gradeId = null;
		 try {
			 ProjectGrade pg = new ProjectGrade();
			 gradeId = ObjectId.get().toString();
			 pg.setId(gradeId);
			 pg.setProjectId(projectId);
			 pg.setGrade(Integer.valueOf(grade));
			 pg.setTime(new Date());
			 pg.setEmployeeId(UserUtils.getUserId());
			 projectGradeServiceImpl.save(pg);
			 //更新项目评级等级
			 ProjectWithBLOBs record = new ProjectWithBLOBs();
			 record.setId(projectId);
			 record.setGrade(Integer.valueOf(grade));
			 projectServiceImpl.updateById(record);
		} catch (Exception e) {
			LOGGER.error("update Project Grade error, error=[{}]", e.getMessage());
		}
		return gradeId;
	}

	/**
     * 删除项目附件
     * @param id 要删除的项目附件ID
     */
	@ResponseBody
	@RequestMapping("/delete/{id}")
	public JsonBean delete(@PathVariable("id") String id) {
		JsonBean bean = new JsonBean();
		try {
			File file = new File(projectAttachmentServiceImpl.get(id).getUrl());
			LOGGER.info("delete projectAttachment params(id)=[{}].", id);
			if (file.exists()) {
				File parent = file.getParentFile();
				if (file.delete()) {
					parent.delete();
				}
			}

			int result = projectAttachmentServiceImpl.deleteById(id);

			if (result == 1) {
				bean.setMessage(SUCCESS);
				bean.setCode(1);
				LOGGER.info("delete projectAttachment success, id=[{}].", id);
			} else {
				bean.setMessage(ERROR);
				LOGGER.error("delete projectAttachment error.");
			}
		} catch (Exception e) {
			LOGGER.error("delete projectAttachment error, id=[{}], errorMsg=[{}].", id, e.getMessage());
			bean.setMessage(ERROR);
		}
		return bean;
	}
    
    /**
     * 项目附件重命名
     * @param model
     */
    @ResponseBody
    @RequestMapping("/rename")
    public JsonBean rename(@RequestBody ProjectAttachment model) {
		JsonBean jsonBean = new JsonBean();
		try {
			String id = model.getId();
			String filename = model.getContractName();// 前端传过来是没有带后缀
			LOGGER.info("request update file name, id=[{}],filename=[{}]", id, filename);

			if (!StringUtils.isBlank(id) && !StringUtils.isBlank(filename)) {
				ProjectAttachment eAttachment = projectAttachmentServiceImpl.get(id);
				String oldFilename = eAttachment.getContractName();
				LOGGER.info("query EnterpriseAttachment by id, id=[{}],filename=[{}]", id, oldFilename);

				filename = filename + eAttachment.getFileType();// 补上后缀
				if (!filename.equalsIgnoreCase(oldFilename)) {// 文件如果不存在则先通过页面删除
					String filepath = eAttachment.getUrl();
					File file = new File(filepath);
					if (file.exists()) {
						String newFilepath = filepath.replace(oldFilename, filename);
						File newFile = new File(newFilepath);
						boolean flag = file.renameTo(newFile);
						if (flag) {
							model.setContractName(filename);
							model.setUrl(newFilepath);
							int result = projectAttachmentServiceImpl.updateById(model);
							if (result == 1) {
								jsonBean.setMessage(SUCCESS);
								jsonBean.setCode(1);
								LOGGER.info("update ProjectAttachment record success.");
							} else {
								jsonBean.setMessage(ERROR);
								LOGGER.error("update ProjectAttachment record error.");
							}
						}
					}
				}
			}
		} catch (Exception e) {
			LOGGER.error("update ProjectAttachment record error, errorMsg=[{}].", e.getMessage());
			jsonBean.setMessage(ERROR);
		}
		return jsonBean;
	}
    
    /**
	 * 根据项目id获取它的相关附件列表
	 * 
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/query/{projectId}")
	public JsonBean query(@PathVariable("projectId") String projectId) {
		JsonBean jsonBean = new JsonBean();
		try {
			LOGGER.info("request relatedFile list, projectId=[{}]", projectId);

			Map<String, Object> maps = new HashMap<String, Object>();
			putRelatedFile(projectId, maps);
			jsonBean.setCode(1);
			jsonBean.setData(maps);
			jsonBean.setMessage(SUCCESS);
			return jsonBean;
		} catch (Exception e) {
			LOGGER.error("request relatedFile list error, msg=[{}]", e.getMessage());
			jsonBean.setCode(0);
			jsonBean.setMessage("request relatedFile list error");
			return jsonBean;
		}
	}
	
	/**
	 * 获取项目相关附件信息
	 * @param enterpriseId
	 * @param maps
	 */
	private void putRelatedFile(String projectId, Map<String, Object> maps) {
		List<ProjectAttachment> list = new ArrayList<ProjectAttachment>();
		if (!StringUtils.isBlank(projectId)) {
			ProjectAttachment EParam = new ProjectAttachment();
			EParam.setProjectId(projectId);
			EParam.setType(1);
			list = projectAttachmentServiceImpl.pagedList(EParam);
			maps.put("project", projectAttachmentServiceImpl.get(projectId));
		}
		maps.put("projectAttachmentList", list);// 将model放入视图中，供页面视图使用
	}
}
